import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store'

const instance = axios.create({
  baseURL: 'http://192.168.1.7:3000/',
  timeout: 5000,
  headers: {
    'X-Custom-Header': 'foobar',
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(function (config) {
  // 在请求之前做些什么
  // 开启loading
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })

  const token = store.state.user.userInfo.token
  if (token) {
    config.headers['Access-Token'] = token
    config.headers.platfrom = 'H5'
  }

  return config
}, function (error) {
  //
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(function (response) {
  //
  Toast.clear()
  return response.data
}, function (error) {
  //
  return Promise.reject(error)
})

export const GetImgCaptchaDataFromSrv = () => {
  return instance.get('/captchaImage')
}

export const GetSmsCodeDataFromSrv =
(captchaCode, captchaKey, mobile) => {
  const postObj = {
    form: {
      captchaCode,
      captchaKey,
      mobile
    }
  }
  console.log('GetSmsCodeDataFromSrv', postObj)
  return instance.get('/getSmsCode', postObj).then(res => {
    // 本地模拟服务器校验结果
    if (captchaCode !== captchaKey) {
      const errorMsg = '图形验证码验证错误'
      Toast.fail(errorMsg)
      return Promise.reject(errorMsg)
    }

    return res
  })
}

export const LoginToSrv =
(mobile, smsCode) => {
  const postObj = {
    form: {
      isParty: false,
      mobile,
      partyData: {},
      smsCode
    }
  }
  console.log('LoginToSrv', postObj)

  const resTmp = instance.get('/login', postObj).then(res1 => {
    // 本地模拟服务器校验结果
    if (smsCode !== '123456') {
      // 检验失败，添加错误吗
      res1.status = 401
      res1.message = '检验失败，请输入正确的验证码'

      Toast.fail(res1.message)
      return Promise.reject(res1.message)
    }
    // console.log('LoginToSrv', res1)
    return res1
  })

  return resTmp
}

// user
export const GetUserInfoFromSrv = () => {
  return instance.get('/userInfo')
}

export const AddUserBalanceOfSrv = async (value) => {
  const userInfo = await GetUserInfoFromSrv()
  userInfo.balance += value

  return instance.patch('/userInfo', {
    balance: userInfo.balance
  })
}

// 首页
export const GetHomeDataFromSrv = () => {
  return instance.get('/pageDetail', {
    params: {
      pageId: 0
    }
  })
}

// 搜索
export const GetGoodsListFromSrv = (obj) => {
  return instance.get('/goodsList')
}

// 分类
export const GetCategoryListFromSrv = (obj) => {
  return instance.get('/categoryList')
}

// 商品详情
export const GetGoodsDetailDataFromSrv = (id) => {
  return instance.get('/goodsDetailList', {
    params: {
      id: 10014
    }
  })
}

// 商品评论
export const GetGoodsCommentsDataFromSrv = (id, count) => {
  return instance.get('/goodsComments', {
    params: {
      id: 10014
    }
  })
}

// 购物车
export const AddGoodsToSrvCart = (goods, addCount, skuId) => {
  return instance.post('/cartGoodsList', {
    goods,
    count: addCount,
    skuId
  })
}

export const GetCartGoodsListFromSrv = () => {
  return instance.get('/cartGoodsList')
}

export const ChangeCountOfSrvCart = (id, count, goodsSkuId) => {
  return instance.patch(`cartGoodsList/${id}`, {
    count
  })
}

export const DelFromSrvCart = (id) => {
  return instance.delete(`cartGoodsList/${id}`)
}

export const AsyncDelSelectOfSrvCart = async (cartItemIdList) => {
  cartItemIdList.forEach(async (id) => {
    await DelFromSrvCart(id)
  })
}

// 地址
export const GetUserAddressListFromSrv = () => {
  return instance.get('/userAddressList')
}

// 订单
export const GetDDFromSrv = (mode, obj) => {
  return instance.get('/aa', {
    params: {
      mode,
      delivery: 10, // 10 - 快递配送 , 20 - 门店自提
      couponId: 0, // 优惠券id
      isUsePoints: 0, // 是否使用积分
      ...obj // 将obj动态展开
    }
  })
}

export const AddToOrderListOfSrv = (order) => {
  return instance.post('/orderList', order)
}

export const GetOrderListFromSrv = () => {
  return instance.get('/orderList')
}

function repair (i) {
  if (i >= 0 && i <= 9) {
    return '0' + i
  } else {
    return i
  }
}

function getCurrentTime () {
  const date = new Date()// 当前时间
  const year = date.getFullYear() // 返回指定日期的年份
  const month = repair(date.getMonth() + 1)// 月
  const day = repair(date.getDate())// 日
  const hour = repair(date.getHours())// 时
  const minute = repair(date.getMinutes())// 分
  const second = repair(date.getSeconds())// 秒

  // 当前时间
  const curTime = year + '-' + month + '-' + day +
          ' ' + hour + ':' + minute + ':' + second
  return curTime
}

export const SubmmitOrderToSrv = async (order, costValue) => {
  await order.cartGoodsList.forEach(async (item) => {
    await DelFromSrvCart(item.id)
  })

  order.createdTime = getCurrentTime()
  await AddToOrderListOfSrv(order)

  await AddUserBalanceOfSrv(-costValue)
}
